from DatabaseConnector import connection
import sys

_DEBUG_ = True
class IndexUtility:
    def __new__(cls, *args, **kargs):
        if cls.instance is None:
            cls.instance = object.__new__(cls, *args, **kargs)
        return cls.instance   
    
    def __init__(self):
        self.concept_idx = {}
#        self.patient_record = {}
#        self.load_index()
#        print self.concept_idx
#        self.load_patient_record()
#        print self.patient_record        
        
    def load_index(self):
        cursor = connection.cursor()
        cursor.execute("select concept_id, request_id_list from snomed.index_concept")
        for tuple in cursor:
            self.DecomposeRequest(tuple[0], tuple[1])
        cursor.close()
        return
            
    def load_patient_record(self):
        if _DEBUG_:
            sys.stderr.write("Loading patient record..")
        cursor = connection.cursor()
        cursor.execute("select patientid, requestid from hosrep.request_table")
        for i,tuple in enumerate(cursor):
            if _DEBUG_:
                     if i % 10000 == 0:
                         sys.stderr.write(".")
            if self.patient_record.has_key(str(tuple[0])) == False:
                self.patient_record[str(tuple[0])] = []
            self.patient_record[str(tuple[0])].append(str(tuple[1]))
        cursor.close()
        if _DEBUG_:
                sys.stderr.write(" %s entries\n" % i)
        return
#                print self.patient_record
    def IndexInstance(self, conceptids):
        cursor = connection.cursor()
        sql = "select concept_id, request_id_list from snomed.index_concept where concept_id in ('"
        for i,conceptid in enumerate(conceptids):
            sql = sql + conceptid
            if i < len(conceptids) -1:
                sql = sql + "','"
        sql = sql + "')"
        cursor.execute(sql)
        for i,tuple in enumerate(cursor):
#            print i
            self.DecomposeRequest(tuple[0], tuple[1])
#        print self.concept_idx
        return
            
    def DecomposeRequest(self, concept_id, req_string):
        req_seg = req_string.split(";")
        for req_seg_ in req_seg:
            for req_seg_tail in req_seg_.split(":")[1].split(","):
                if self.concept_idx.has_key(self.DecodeRequestID(req_seg_.split(":")[0], req_seg_tail)) == False:
                    self.concept_idx[self.DecodeRequestID(req_seg_.split(":")[0], req_seg_tail)] = 0
#        print "Concept ID:" + concept_id
#        print len(self.concept_idx)
        return
    
    def DecodeRequestID(self, codehead, codetail):
        return int(codehead)*1000 + int(codetail)
            
if __name__ == "__main__":
    idx = IndexUtility()
#    print idx.patient_record["1004"]
    idx.IndexInstance("263787003")
    print idx.concept_idx
